from django.shortcuts import render, reverse, redirect
from stu_addr import models
from django.http import HttpResponseRedirect


def stuinfo(request):
    stuinfo_list_obj = models.stuinfo.objects.all()
    return render(request, 'info.html', {'stuinfo_list': stuinfo_list_obj})


def add_stuinfo(request):
    if request.method == "POST":
        stu_id = request.POST.get('id')
        name = request.POST.get('name')
        math = request.POST.get('math')
        chinese = request.POST.get('chinese')
        english = request.POST.get('english')
        models.stuinfo.objects.create(id=stu_id, name=name, math=math, chinese=chinese, english=english)
        return redirect('stuinfo')
    elif request.method == "GET":
        return render(request, 'add.html')


def del_stuinfo(request):
    id = request.GET.get('id')
    models.stuinfo.objects.filter(id=id).delete()
    return redirect('stuinfo')


def mod_stuinfo(request):
    if request.method == 'GET':
        id = request.GET.get('id')
        stu_detail = models.stuinfo.objects.get(id=id)
        context = {'stu_detail': stu_detail}
        print(stu_detail.id)
        return render(request, 'hoourt.html', context=context)
    if request.method == "POST":
        stu_id = request.POST.get('id')
        name = request.POST.get('name')
        math = request.POST.get('math')
        chinese = request.POST.get('chinese')
        english = request.POST.get('english')

        info = models.stuinfo.objects.get(id=stu_id)
        info.name = name
        info.math = math
        info.chinese = chinese
        info.english = english
        info.save()

        return redirect('stuinfo')